/**
 * 游戏攻击脚本
 * Author           : wangjun
 * Time             :2017-04-15
 */


var com = require('Common')
var bulletId = 0;
cc.Class({
    extends: cc.Component,

    
    onLoad: function () {
        this.plane = cc.find("plane_hero", this.node.parent);
        this.map = cc.find("Map",this.node.parent);
        this.avatar = cc.find('plane_hero/spr_avatar',this.node.parent);

    },

    createBullet: function(){
  
        var plane = this.plane;
        var map = this.map;
        var angle = this.avatar.rotation;
        cc.loader.loadRes("persist/prefab/effect_bullet", function (err, prefab) {
        com.bullets.bull[bulletId] = cc.instantiate(prefab);
        plane.addChild(com.bullets.bull[bulletId]);
        com.bullets.bull[bulletId].direct = angle;
        com.bullets.bull[bulletId].setPosition(0,0);
        });

        ++bulletId;
      
    },


    updateBulletPos: function(){
//        var angle = this.avatar.rotation;

        for (var key in com.bullets.bull){
            var bullet = com.bullets.bull[key];            
            var pos    = bullet.getPosition();
            bullet.setPositionX(pos.x + 8 * Math.cos(-bullet.direct*Math.PI /180));
            bullet.setPositionY(pos.y + 8 * Math.sin(-bullet.direct*Math.PI /180));

           // 子弹飞行距离
             if ( Math.sqrt(bullet.getPositionX()*bullet.getPositionX()+ bullet.getPositionY()*bullet.getPositionY()) >500){
                 bullet.parent.removeChild(bullet, true);
                 delete com.bullets.bull[key];
             }
        }
    },
    checkHit : function(enemys,bullets){
         
         for (var bulletKey = 0;bulletKey <= bullets.length;bulletKey++){
            var bullet = bullets[bulletKey];

            for (var enemyKey = 0;enemyKey <= enemys.length;enemyKey++){    
                var enemy = enemys[enemyKey];

                if(enemy != undefined && bullet != undefined)
                if (enemy.getBoundingBox().contains(bullet.getPosition())){
                    
                 //   this._effect = this.node.getComponent(cc.Animation);
                    bullet.parent.removeChild(bullet, true);
                    delete bullets[bulletKey];

                    enemy.parent.removeChild(enemy, true);
                    delete enemys[enemyKey];
                    break;
                }
            }
        }

    },
     update: function (dt) {

    this.updateBulletPos(dt);

    this.checkHit(com.enemys,com.bullets.bull,dt);

     },
});
